M/s VIKASH TECH - How to Implement Google QAuth Authentication | Google Login - PHP MySQL

PHP Google OAuth API allows users to login into a website with their Google credentials. A user with a Google account need not remember yet another username/password for a web

 · 4 min read

PHP Google OAuth API allows users to login into a website with their Google credentials. A user with a Google account need not remember yet another username/password for a web application. This PHP tutorial is to learn about setting up an authentication system for your custom web application using Google OAuth.

We are using Google OAuth Version 2.0 API.

Google OAuth Authentication

php_google_oauth_login
  1. Send client authentication requests via Google OAuth API.
  2. Google OAuth server validates against its backend and returns authentication code.
  3. The client executes a callback PHP script.
  4. Application callback script sends the authentication code for getting the access token.
  5. Google API responds to the client with a success or failure token.

Google OAuth Prerequisites

  • Create a Google API project and get OAuth credentials.
  • Download / Install PHP Google API client library.

Steps to implement Google authentication

  1. Create / Send authentication request.
  2. Access user data from Google.

Create Google OAuth Credentials

  • Create a new project and get the corresponding OAuth credentials using the Google developer console page. create_google_project
  • Select APIS & AUTH ‚Äì> APIs from Google project dashboard and enable Google+API. enable_google_api
  • Select APIS & AUTH ‚Äì> credentials from the left menu. get_oauth_credential
  • Click Create new Client ID button and complete data on this wizard. create_client_id
  • After submitting this form, we can get the client Id, secret key and etc as below, google_oauth_client_id
  • Click Create New Key to create server key as Google project‚Äôs developer key. We should keep this key secure.
  • Finally, we have to design a consent screen that will be shown on requesting user data. consent_screen

Note: All the credentials we got from this step will be used later in our code for creating client request.

Download / Install PHP Google API Client Library

For setting the above credentials with our client authentication request, we need to download the Google AP Client Library from the Github repository. After downloading, we should install it into the root directory. And then, we need to include the library source path using the php.ini file or by a dynamic function call.

php.ini setting

include_path=".;C:\xampp\htdocs\phppot_samples\php_google_oauth_login\google-api-php-client\src"

Dynamic setting

ini_set('include_path', 'C:\xampp\htdocs\phppot_samples\php_google_oauth_login\google-api-php-client\src');

PHP Google OAuth Authentication Code

In this code, we need to include the required OAuth service class to access Google API. And then, we have to start the session before sending any data to the browser. The code is,

<?php
session_start();
require_once 'dbcontroller.php';

//Google API PHP Library includes
require_once 'Google/Client.php';
require_once 'Google/Service/Oauth2.php';

// Fill CLIENT ID, CLIENT SECRET ID, REDIRECT URI from Google Developer Console
 $client_id = '<Your-Client-ID>';
 $client_secret = '<Your-Client-Secret-Key>';
 $redirect_uri = '<Callback-URL>';
 $simple_api_key = '<Your-API-Key>';
 
//Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");

//Send Client Request
$objOAuthService = new Google_Service_Oauth2($client);

//Logout
if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
  $client->revokeToken();
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL)); //redirect user back to page
}

//Authenticate code from Google OAuth Flow
//Add Access Token to Session
if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

//Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
}

//Get User Data from Google Plus
//If New, Insert to Database
if ($client->getAccessToken()) {
  $userData = $objOAuthService->userinfo->get();
  if(!empty($userData)) {
	$objDBController = new DBController();
	$existing_member = $objDBController->getUserByOAuthId($userData->id);
	if(empty($existing_member)) {
		$objDBController->insertOAuthUser($userData);
	}
  }
  $_SESSION['access_token'] = $client->getAccessToken();
} else {
  $authUrl = $client->createAuthUrl();
}
require_once("loginpageview.php")
?>

In the above code replace your own OAuth credentials and send them to the Google OAuth Service class. Using this class instance we can access user data if the client access token is found. Otherwise, the login button will be shown which redirects to Google OAuth URL. The login  view page code is,

<HTML>
<HEAD>

<style>
	.box {font-family: Arial, sans-serif;background-color: #F1F1F1;border:0;width:340px;webkit-box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.3);box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.3);margin: 0 auto 25px;text-align:center;padding:10px 0px;}
	.box img{padding: 10px 0px;}
	.box a{color: #427fed;cursor: pointer;text-decoration: none;}
	.heading {text-align:center;padding:10px;font-family: 'Open Sans', arial;color: #555;font-size: 18px;font-weight: 400;}
	.circle-image{width:100px;height:100px;-webkit-border-radius: 50%;border-radius: 50%;}
	.welcome{font-size: 16px;font-weight: bold;text-align: center;margin: 10px 0 0;min-height: 1em;}
	.oauthemail{font-size: 14px;}
	.logout{font-size: 13px;text-align: right;padding: 5px;margin: 20px 5px 0px 5px;border-top: #CCCCCC 1px solid;}
	.logout a{color:#8E009C;}
</style>
</HEAD>
<BODY>
<div class="heading">PHP Google OAuth 2.0 Login</div>
<div class="box">
  <div>
	<!-- Show Login if the OAuth Request URL is set -->
    <?php if (isset($authUrl)): ?>
	  <img src="images/user.png" width="100px" size="100px" /><br/>
      <a class='login' href='<?php echo $authUrl; ?>'><img class='login' src="images/sign-in-with-google.png" width="250px" size="54px" /></a>
	<!-- Show User Profile otherwise-->
    <?php else: ?>
	  <img class="circle-image" src="<?php echo $userData["picture"]; ?>" width="100px" size="100px" /><br/>
	  <p class="welcome">Welcome <a href="<?php echo $userData["link"]; ?>" /><?php echo $userData["name"]; ?></a>.</p>
	  <p class="oauthemail"><?php echo $userData["email"]; ?></p>
	  <div class='logout'><a href='?logout'>Logout</a></div>
    <?php endif ?>
  </div>
</div>
</BODY>
</HTML>
</HTML>

Output

While running user authentication code we can see,

google_login

By successful login, Google OAuth flow will redirect to the page we have specified.

google_user_info

For complete source code, click the download button below.

If you like the blog, hit the like button, share it and put your comments below if you want any help.


No comments yet.

Add a comment
Ctrl+Enter to add comment